<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <title>sMAP Dashboard</title>
    <link href="/media/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="/media/smap/css/vquery.css" rel="stylesheet" media="screen">
    <link href="/media/smap/css/status.css" rel="stylesheet" media="screen">
    <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
    <link rel="stylesheet" type="text/css" href="/media/smap/css/bootstrap-datetimepicker.min.css">

    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-migrate/1.1.1/jquery-migrate.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.0.1/d3.v3.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/datatables/1.9.4/jquery.dataTables.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>
    
    <script src="/media/smap/js/vquery.js"></script>
    <script src="/media/smap/js/bootstrap-datetimepicker.min.js"></script>
    <script src="/media/smap/js/miuri.js"></script>
    <script src="/media/smap/js/smaputil.js"></script>

    <style>
      #dashboard {
        font: 12px sans-serif;
      }     
      .axis path,
      .axis line {
        fill: none;
        stroke: #000;
        shape-rendering: crispEdges;
      }
      .line {
        stroke-width: 1px;
      }
      #myTab {
        margin: 5px 0px 0px 5px;
      }
      .loading {
        display:    none;
        position:   fixed;
        z-index:    1000;
        top:        0;
        left:       0;
        height:     100%;
        width:      100%;
        background: rgba( 250, 250, 250, .6 ) 
                    url('/media/smap/img/ajax-loader.gif') 
                    50% 50% 
                    no-repeat;
      }
    </style>
  </head>

  <body>
    <ul class="nav nav-tabs" id="myTab">
      <li><a id='tstreams' href="#streams" data-toggle="tab">Streams</a></li>
      <li><a id='tdashboard' href="#dashboard" data-toggle="tab">Dashboard</a></li>
      <li class="dropdown">
        <a id='tutil' href="#" class="dropdown-toggle" data-toggle="dropdown"><i class='icon-wrench'></i></a>
        <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
          <li><a onclick='getPermalink();' href="#">Permalink</a></li>
          {% if user.is_active %}
            <li><a onclick='logout();' href="#">Log out</a></li>
          {% else %} 
            <li><a onclick='login();' href="#">Log in</a></li>
          {% endif %}
        </ul>
      </li>
    </ul>

    <div class="tab-content">
      <div class="tab-pane fade in" id="streams" style="margin-top:10px; margin: 10px auto; width:99%;">
      
        <div class="left">
          <div id="vquery"></div>
          <div id='stream-div' style="height: 90%; overflow: auto; margin-top:10px;"></div>
        </div> 

        <div class="right" style="height: 100%;">
          <div id="setup-charts">
            Setup plots
            <br/>
              <div id="start-time" class="input-append date">
                <input data-format="MM/dd/yyyy hh:mm" type="text"></input>
                <span class="add-on">
                  <i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
                </span>
             </div>
             <div id="end-time" class="input-append date">
               <input data-format="MM/dd/yyyy hh:mm" type="text"></input>
               <span class="add-on">
                 <i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
               </span>
             </div>
          </div>
          
          <div id="paths-cont">
            Selected streams <button id='btn-clear' style='margin-bottom: 5px;' class='btn btn-mini'>clear</button>
            <table id ="paths-table" class="table table-hover table-bordered table-condensed">
              <thead><tr><th width="85%">Path</th><th style='text-align:center'>Remove</th></tr></thead>
              <tbody></tbody>
            </table>
          </div>
          <div id="metadata-cont">
            Common metadata
            <pre id="common-metadata" class="prettyprint"></pre>
          </div>
          <div id="single-stream-metadata-cont" style="display:none">
            Stream metadata
            <pre id="single-stream-metadata" class="prettyprint"></pre>
          </div>
          <div id="edit-metadata">
            Add or edit tags 
            <div id="metadata-inside">
              <input id="metadata-tag" class="typeahead" type="text"> =
              <input id="metadata-val" type="text">
              <button class="btn" id="metadata-set" style="margin-bottom: 10px;">set</button>
            </div>
          </div>

        </div>

        <div id="confirm" class="modal hide">
          <div id="confirm-body" class="modal-body"></div>
          <div class="modal-footer">
            <button type="button" data-dismiss="modal" class="btn">Nevermind</button>
            <button type="button" id="modal-confirm" class="btn btn-primary">Confirm</button>
          </div>
        </div>
      </div>
      
      <div class="tab-pane fade" id="dashboard"></div>
    <div class='loading'></div>     
    </div>
    

    <script src="/media/smap/js/tags.js"></script>
    <script>

    $(function() {
      window._uri = new miuri(window.location.href)
      var ts_start = parseFloat(_uri.query('start'))
      var ts_end = parseFloat(_uri.query('end'))
      var uuids = _uri.query('uuids')
      var start, end
      window._streams = []
      var view = _uri.query('view')
      view = view || 'streams';

      switch(view){
        case 'streams':
          $('#myTab a[href="#streams"]').tab('show');
          break;
        case 'dashboard':
          $('#myTab a[href="#dashboard"]').tab('show');
          break;
      }

      if (ts_start & ts_end) { 
        start = new Date(ts_start);
        end = new Date(ts_end);
      } else { 
        end = new Date();
        start = new Date();
        start.setHours(start.getHours() - 12)
      }
      $('#start-time').datetimepicker();
      $('#end-time').datetimepicker(); 
      $('#start-time').data('datetimepicker').setLocalDate(start);
      $('#end-time').data('datetimepicker').setLocalDate(end);

      $("#dropdown-toggle").dropdown()
      
      function renderDashboard(){
        $('#dashboard').empty();
        var start = $('#start-time').data('datetimepicker').getLocalDate();
        var end = $('#end-time').data('datetimepicker').getLocalDate();
        start = start.getTime();
        end = end.getTime();
        var uids = _.pluck(_streams, 'uuid')
        smaputil.getStreamData(uids, start, end, renderStack)
        $('.loading').show()
        $('#myTab a[href="#dashboard"]').tab('show');
      }
      
      $('#tdashboard').click(renderDashboard)

      $('#btn-clear').click(function(){
        $('#paths-table tbody').empty()
        _streams = []
        $('#common-metadata').empty()
      });

      if (uuids) {
        uuids = uuids.split(',') 
        smaputil.getMetadata(uuids, ['uuid', 'Path'], function(res){
          _.each(res, function(el){
            _streams.push({'path':el.Path, 'uuid':el.uuid})
            $('#paths-table tbody').append('<tr id='+el.uuid+'><td>'+el.Path+'</td><td style="text-align: center"> \
              <button id="remove-'+el.uuid+'"  class="btn btn-mini btn-remove" type="button">X</button></td></tr>')      
            $('#remove-'+el.uuid).click(removeRow);
          });
          
          renderCommonMetadata(uuids);
      
          if(view=='dashboard') {
            renderDashboard();
          }
        });
      }
    });

    var config = {
       "chart_el": "#dashboard",
       "width": $(window).width(),
       "height": $(window).height() - 60,
       "margin": {top: 20, right: 20, bottom: 20, left: 60},
       "color": "red",
    }

    function getValsFromTS(ts, readings){
      return _.map(readings, function(d){
        var ts_array = _.map(d, function(e){
          return e.timestamp
        });
        var val_array = _.map(d, function(e){
          return e.reading
        });
        var ts_span = _.sortedIndex(ts_array, ts)
        if (ts_span == 0 | ts_span == readings.length - 1){
          return Number.NaN
        } else {
          var ts_1 = ts_array[ts_span - 1]
          var ts_2 = ts_array[ts_span]
          var val_1 = val_array[ts_span - 1]
          var val_2 = val_array[ts_span]
          var s = (val_2 - val_1) / (ts_2 - ts_1)
          return (val_1 + s * (ts - ts_1))
        }
      });
    }

    function renderMetadata(o){
      _.each(o, function(e){
        d3.select("#path-text-"+e.uuid)
          .text(e.Path)
        d3.select("#unit-text-"+e.uuid)
          .text(e.Properties.UnitofMeasure)
      });
      $('.loading').hide()
    }

    function renderStack(data){
      var chart_el = config.chart_el;
      var margin = config.margin;
      var height = config.height - margin.top - margin.bottom;
      var width = config.width - margin.left - margin.right;
      var uuids = _.pluck(data, 'uuid')
      var readings = smaputil.smaptod3(data)
      var nseries = readings.length;
      var h = Math.floor(height / nseries);

      var x = d3.time.scale()
        .range([0, width])
      var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");
      
      x.domain(d3.extent(_.flatten(readings), function(d){
        return d.timestamp;
      }));

      var svg = d3.select(chart_el).append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");      

      svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

      var bg, even = true;
      var precision = [];
      for (var i = 0; i < nseries; i++){
        var y = d3.scale.linear()
          .range([height - h*i, height - h*(i+1)])
        var yAxis = d3.svg.axis()
          .scale(y)
          .orient("left");
        var extent = d3.extent(readings[i], function(d){
          return d.reading
        });
        var range = extent[1] - extent[0]
        precision.push(Math.max(0, 2 - range.toFixed(0).length))
        
        y.domain(extent);
        yAxis.ticks(0);
        var area  = d3.svg.area()
          .x(function(d) { return x(d.timestamp); })
          .y0(height - h*i)
          .y1(function(d) { return y(d.reading); });

        var line = d3.svg.line()
          .x(function(d) { return x(d.timestamp); })
          .y(function(d) { return y(d.reading); });
          
        var h_col = 210; //+ Math.floor(i*(180/nseries))
        var col_hsl_series = "hsl(" + h_col.toString() + ", 90%, 70%)"
        var col_hsl_path = "hsl(" + h_col.toString() + ", 90%, 15%)"
        svg.append("path")
          .datum(readings[i])
          .attr("class", "line")
          .attr("d", area)
          .attr("fill", col_hsl_series)
       
        svg.append("line")
           .attr("x1", 0)
           .attr("x2", width)
           .attr("y1", height - h*(i+1))
           .attr("y2", height - h*(i+1))
           .attr("stroke", "grey")
           .attr("opacity", 0.3)
        
        var unit_translate = height - h*(i+1) + h/2
        var unit_transform = "translate(-45, " + unit_translate.toString() + ") rotate(-90)"   
        svg.append("g")
          .attr("class", "y axis")
          .call(yAxis)
        .append("text")
          .attr("class", "unit-text")
          .attr("id", "unit-text-" + uuids[i])
          .attr("transform", unit_transform)
          .attr("dy", ".71em")
          .attr("font-size", 14)
          .style("text-anchor", "middle")

        try {
          svg.append("text")
            .attr("class", "unit-text")
            .attr("id", "max-text-" + i)
            .attr("x", -3)
            .attr("y", height - h*(i+1) + 13)
            .style("text-anchor", "end")
            .text(extent[1].toFixed(precision)) 

          svg.append("text")
            .attr("class", "unit-text")
            .attr("id", "max-text-" + i)
            .attr("x", -3)
            .attr("y", height - h*i - 5)
            .style("text-anchor", "end")
            .text(extent[0].toFixed(precision)) 
         } catch(err) {
           console.log("Stream with uuid " + uuids[i] + " contains no data in this range")
         }

        svg.append("text")
          .attr("class", "path-text")
          .attr("id", "path-text-" + uuids[i])
          .attr("x", 10)
          .attr("y", height - h*i - 20)
          .attr("dy", ".71em")
          .attr("font-size", 18)
          .attr("fill", col_hsl_path)
          .style("text-anchor", "start")

        svg.append("text")
          .attr("class", "rule-text")
          .attr("font-size", 20)
          .attr("id", "rule-text-" + i)
          .attr("y", height - h*(i+1) + 20)
          .style("text-anchor", "end")
      }

      svg.append("rect")
        .attr("id", "rule")
        .attr("x", 0)
        .attr("y", 0)
        .attr("width", 1)
        .attr("height", height)
        .attr("opacity", 0.7)

      d3.select("svg").on('mousemove', function(){
        var xpos = d3.event.pageX - margin.left - margin.right + 18;
        if (xpos < 0) xpos = 0
        if (xpos > width) xpos = width
        d3.select('#rule').attr('x', xpos);
        var ts = x.invert(xpos).getTime()
        var vals = getValsFromTS(ts, readings)
        z = _.zip(vals, precision)
        vals = _.map(z, function(w){
          if (isNaN(w[0])) return ""
          return w[0].toFixed(w[1])
        });
        var text_el
        for (var i = 0; i < nseries; i++){
          text_el = d3.select("#rule-text-"+i)
          text_el.text(vals[i])
          text_el.attr("x", xpos - 5)
        }
      });

      var tags = ['uuid', 'Path', 'Properties/UnitofMeasure']
      smaputil.getMetadata(uuids, tags, renderMetadata)      
    }

    $('#myTab a').click(function (e) {
      e.preventDefault();
      var tab = $(this).attr('id')
      if (tab!='tutil'){
        $(this).tab('show');
      }
    })
 
    function getPermalink(){
      var permalink = new miuri()
    
      permalink.host(_uri.host())
      permalink.path(_uri.path())
      permalink.protocol(_uri.protocol())

      var uuids = _.pluck(_streams, 'uuid')
      var s = $('#start-time').data('datetimepicker').getLocalDate().getTime();
      var e = $('#end-time').data('datetimepicker').getLocalDate().getTime();
      var v = $("#myTab li.active a").attr('id').substr(1)
      console.log(v)
      permalink.query({
        uuids: uuids.join(','),
        start: s,
        end: e,
        view: v
      })
      window.location.href = permalink.toString()
    }
    function login(){
      window.location.href = "/dashboard/?login="
    }
    function logout(){
      window.location.href = "../../admin/logout"
    }
    </script>
    
    
  </body>
</html>
